<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
use function Pest\Laravel\json;

class WechatMiddleware
{
    /**
     * Handle an incoming request.
     * @param Request $request
     * @param Closure(Request): (Response) $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $user = $request->get('userInfo');
        if ($user || $request->input('tenantId'))
        {
            $tenantId = !$user?$request->input('tenantId'):$user['tenantId'];
        }else{
            return response()->json(['code'=>400,'message'=>'参数错误！']);
        }

        $where = array(
            ['tenantId',$tenantId],
            ['field','wechat']
        );
        $config_obj = DB::table('setting')->where($where)->get()->first();
        $config = json_decode($config_obj->data,true);
        Config::set('easywechat.official_account.default.app_id',$config['appid']);
        Config::set('easywechat.official_account.default.secret',$config['appsecret']);
        return $next($request);
    }
}
